package com.qf.controller;

import com.qf.common.ResultEntity;
import com.qf.entity.Order;
import com.qf.entity.OrderDetail;
import com.qf.feign.api.OrderService;
import com.qf.service.IStockService;
import com.qf.vo.GoodsStockInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/stockController")
public class StockController {

    @Autowired
    private IStockService stockService;

    @Autowired
    private OrderService orderService;

    /**
     * 扣减库存
     *
     * @param list
     * @return
     */
    @RequestMapping("/lockGoodsStock")
    public Boolean lockGoodsStock(@RequestBody List<GoodsStockInfo> list) {
        return stockService.lockGoodsStock(list);
    }

    @RequestMapping("/unlockGoodsStock/{oid}")
    public Boolean unlockGoodsStock(@PathVariable String oid) {

        // 根据oid查询这个订单买了哪些商品以及数量
        Order order = orderService.getOrderById(oid);

        // 2、创建一个集合，用来装需要被释放的库存商品
        List<GoodsStockInfo> list = new ArrayList<>();

        for (OrderDetail orderDetail : order.getOrderDetails()) {
            GoodsStockInfo goodsStockInfo = new GoodsStockInfo();
            goodsStockInfo.setGid(orderDetail.getGid());
            goodsStockInfo.setWid(1);
            goodsStockInfo.setSum(orderDetail.getSum());
            list.add(goodsStockInfo);
        }

        // 3.释放库存
        stockService.unlockGoodsStock(list);

        return true;
    }
}
